#pragma once

#include <iostream>
#include "log.hpp"
#include "Protocal.hpp"

enum err_symbol
{
    div_zero = 1,
    mod_zero
};

class ServerCal
{
public:
    ServerCal()
    {
    }

    Response Calculatate(Requset &req)
    {
        Response resp(0, 0);
        //std::cout << "客户端请求的数据"  << std::endl;
        //req.Print();
        switch (req.op_)
        {
        case '+':
            resp.result_ = req.Getx() + req.Gety();
            break;
        case '-':
            resp.result_ = req.Getx() - req.Gety();
            break;
        case '*':
            resp.result_ = req.Getx() * req.Gety();
            break;
        case '/':
            if (req.Gety() == 0)
            {
                resp.code_ = div_zero;
                break;
            }
            resp.result_ = req.Getx() / req.Gety();
            break;
        case '%':
            if (req.Gety() == 0)
            {
                resp.code_ = mod_zero;
                break;
            }
            resp.result_ = req.Getx() % req.Gety();
            break;
        default:
            break;
        }


        return resp;
    }

    std::string Calculator(std::string &package)
    {
        //std::cout <<"package" << package << std::endl;
        // 移除报头
        std::string context;
        bool rDecode = Decode(package, &context);
        if(!rDecode) return "";

        //std::cout <<"context\n" << context << std::endl;
        //反序列化客户
        Requset req;
        req.Deserialize(context);

        // std::cout << " 反序列化客户"<< std::endl;
        // req.Print();

        //计算数据
        Response resp;
        resp =  Calculatate(req);

        //std::cout << "计算数据"<< std::endl;
        //resp.Print();

        sleep(3);

        //序列化服务
        std::string in;
        bool r = resp.Serialize(&in);
        if(!r) return "";
        //std::cout << "in: \n"<< in << std::endl;


        //添加报文
        context = "";
        context = Encode(in);

        //std::cout << "添加报文\n"<< std::endl;
        //std::cout << "context" << context << std::endl;

        return context;
    }

    ~ServerCal()
    {
    }
};
